<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// 首页设置  middleware(['web'])->
Route::get('/', function() { return view('welcome'); });
//Route::get('/', 'App\Http\Controllers\Frontend\HomeController@index');


// 接口
Route::match(
    ['post', 'get', 'delete',],
    '/{module?}/{controller?}/{action?}',
    function($module = 'frontend', $controller = 'home', $action = 'index') {
        $request = request();
        $ip      = $request->ip();
        try{
            $post = $request->all();
            // 控制器   中划线 => 驼峰式:大小写
            $controller = ucfirst($controller);
            $module     = ucfirst($module);
            $file       = 'App\Http\Controllers\\'.$module.'\\'.$controller.'Controller';

            // 控制器   中划线 => 驼峰式:大小写
            $file   = str_replace(' ', '', ucwords(str_replace('-', ' ', $file)));
            $action = str_replace(' ', '', ucwords(str_replace('-', ' ', $action)));
            $action = lcfirst($action);


            //var_dump($file);die;
            //var_dump(class_exists($file));
            //var_dump(method_exists($file, $action));

            // 执行请求
            $file   = App::make($file);
            $result = $file->$action($post);

            return $result;
        } catch(\Exception $e){
            // 因为这里没有 专门 的错误操作类继续处理 所以这里只能返回json给前端
            $result = ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'line' => $e->getLine()];
            if($ip == '127.0.0.1'){
                $result['file'] = $e->getFile();
                return json_encode($result);
            } else{
                return json_encode($result);
            }
        }
    }
)->where(['controller' => '[0-9a-zA-Z-]+', 'action' => '[0-9a-zA-Z-]+'])
     ->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class])
     ->name('appapi'); // 统一命令


